<?php


namespace app\shop\validate;

use think\Validate;


/**
 * 商品验证器
 * Class Goods
 * @package app\Goods\validate
 * @author Mr.Liu
 * @create 2021-09-16 14:23
 */
class Goods extends Validate
{

    /**
     * 验证规则
     * @var string[]
     */
    protected $rule = [
        //'name'   => 'unique:shop_goods,status=1',
        'name'                  => 'require|is_goods_unique:shop_goods|max:50|min:1',
        'spec_name'             => 'require',
        'goods_sn'              => 'require',
        'price'                 => 'require',
        'status'                => 'require|integer|between:1,2',
        'is_project'            => 'require|integer|between:1,2',
        'kingdee_code'          => 'require',
        'unit_code'             => 'require'

    ];

    /**
     * 错误信息
     * @var string[]
     */
    protected $message = [
        'name.require'                  => '商品名称必须填写',
        'name.is_goods_unique'          => '商品名称已存在',
        'name.max'                      => '商品名称最多填写50个字符',
        'name.min'                      => '请填写商品名称',
        'goods_sn.require'              => '商品货号必须填写',
        'spec_name.require'             => '商品规格必须填写',
        'price.require'                 => '商品价格必须填写',
        'status.require'                => '状态必须选择',
        'status.integer'                => '状态必须为整数',
        'status.between'                => '状态值不正确',
        'kingdee_code.require'          => '金蝶编码必须填写',
        'unit_code.require'             => '单位金蝶编码必须填写',
        'is_project.require'            => '是否项目必须选择',
        'is_project.integer'            => '是否项目必须为整数',
        'is_project.between'            => '是否项目值不正确',

    ];


    /**
     * 场景
     * @var \string[][]
     */
    protected $scene = [
        'create'            => ['name','spec_name','goods_sn','price','kingdee_code','unit_code','is_project'],
        'update'            => ['id','name','spec_name','goods_sn','price','kingdee_code','unit_code','is_project'],
        'update_status'     => ['status'],
        'batch_create'      => ['name','unit_code','price','kingdee_code','is_project']
    ];


    /**
     * 验证name唯一性
     * @param $value
     * @param $rule
     * @param array $data
     * @param string $field
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @author Mr.Liy
     * @create 2021-09-16 13:45
     */

    public function is_goods_unique($value, $rule, array $data = [], string $field = ''): bool
    {


        $id = $data['id'] ?? 0;
        $where = [
            ['delete_time','=',0],
            ['name','=',trim($value)],
        ];
        if($id){
            $where[] = ['id','<>',$id];
        }
        if(\app\shop\model\Goods::where($where)->value('id')){

            return false;
        }
        return true;

    }


}
